package Chatnetwork1;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 使用线程封装客户发送端
 * 1.发送消息
 * 2.获取消息
 * 3.释放资源
 */
public class Send implements Runnable {
    private BufferedReader console;
    private DataOutputStream dos;
    private Socket client;
    private boolean isRunning;
    private String name;

    public Send(Socket client, String name) {
        isRunning=true;
        this.client = client;
        this.name = name;
        console = new BufferedReader(new InputStreamReader(System.in));
        try {
            dos = new DataOutputStream(client.getOutputStream());
            send(name);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void run() {
        while (isRunning) {
            String msg = this.getStringFromConsole();
            if (!msg.equals("")) {
                this.send(msg);
            }
        }
    }
    //发送消息
    private void send(String msg) {
        try {
            dos.writeUTF(msg);
            dos.flush();
        } catch (IOException e) {
            //释放资源
        }

    }
    //从控制台获取消息
    private String getStringFromConsole() {
        try {
            return console.readLine();
        } catch (IOException e) {
            release();
        }
        return "";
    }
    //释放资源
    private void release() {
        this.isRunning = false;
        Utils.close(dos,client);
    }
}
